import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { AudioState } from '@/types'

export const useAudioStore = defineStore('audio', () => {
  const audio = ref<HTMLAudioElement | null>(null)
  const audioState = ref<AudioState>({
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    speed: 1.0,
    isLooping: false
  })
  
  const currentPoemId = ref<number | null>(null)
  
  // 初始化音频
  const initAudio = (poemText: string, poemId: number) => {
    // 清理之前的音频
    if (audio.value) {
      audio.value.pause()
      audio.value.removeEventListener('loadedmetadata', onLoadedMetadata)
      audio.value.removeEventListener('timeupdate', onTimeUpdate)
      audio.value.removeEventListener('ended', onEnded)
    }
    
    currentPoemId.value = poemId
    
    // 模拟音频文件（实际项目中应该使用真实的音频文件）
    // 这里使用Web Speech API来生成语音
    if ('speechSynthesis' in window) {
      // 如果之前有语音在播放，先停止
      speechSynthesis.cancel()
      
      // 更新状态
      audioState.value = {
        isPlaying: false,
        currentTime: 0,
        duration: 0,
        speed: 1.0,
        isLooping: false
      }
    }
  }
  
  // 播放语音
  const play = () => {
    if (!currentPoemId.value) return
    
    const poemText = getPoemText(currentPoemId.value)
    if (!poemText) return
    
    const utterance = new SpeechSynthesisUtterance(poemText)
    utterance.lang = 'zh-CN'
    utterance.rate = audioState.value.speed
    utterance.volume = 0.8
    
    utterance.onstart = () => {
      audioState.value.isPlaying = true
    }
    
    utterance.onend = () => {
      audioState.value.isPlaying = false
      if (audioState.value.isLooping) {
        setTimeout(() => play(), 500) // 500ms间隔后重新播放
      }
    }
    
    utterance.onerror = () => {
      audioState.value.isPlaying = false
    }
    
    speechSynthesis.speak(utterance)
  }
  
  // 暂停播放
  const pause = () => {
    if (audioState.value.isPlaying) {
      speechSynthesis.cancel()
      audioState.value.isPlaying = false
    }
  }
  
  // 切换播放/暂停
  const togglePlayPause = () => {
    if (audioState.value.isPlaying) {
      pause()
    } else {
      play()
    }
  }
  
  // 设置播放速度
  const setSpeed = (speed: number) => {
    audioState.value.speed = speed
    if (audioState.value.isPlaying) {
      // 重新开始播放以应用新速度
      pause()
      setTimeout(() => play(), 100)
    }
  }
  
  // 切换循环播放
  const toggleLoop = () => {
    audioState.value.isLooping = !audioState.value.isLooping
  }
  
  // 获取古诗文本（模拟从store获取）
  const getPoemText = (poemId: number): string => {
    // 模拟古诗文本
    const poemTexts: Record<number, string> = {
      1: '鹅鹅鹅，曲项向天歌，白毛浮绿水，红掌拨清波。',
      2: '床前明月光，疑是地上霜。举头望明月，低头思故乡。',
      3: '春眠不觉晓，处处闻啼鸟。夜来风雨声，花落知多少。',
      4: '碧玉妆成一树高，万条垂下绿丝绦。不知细叶谁裁出，二月春风似剪刀。',
      5: '锄禾日当午，汗滴禾下土。谁知盘中餐，粒粒皆辛苦？'
      // 可以继续添加更多古诗
    }
    return poemTexts[poemId] || '这是一首美丽的古诗。'
  }
  
  // 清理资源
  const cleanup = () => {
    if (audio.value) {
      audio.value.pause()
      audio.value = null
    }
    speechSynthesis.cancel()
    currentPoemId.value = null
    audioState.value = {
      isPlaying: false,
      currentTime: 0,
      duration: 0,
      speed: 1.0,
      isLooping: false
    }
  }
  
  return {
    audioState,
    currentPoemId,
    initAudio,
    play,
    pause,
    togglePlayPause,
    setSpeed,
    toggleLoop,
    cleanup
  }
})